<?php

namespace App\Http\Services;

use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\Hint;
use App\Http\Model\User;
use App\Http\Model\ColorGift;
use App\Http\Model\ColorGiftRateConfig;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\FinanceDiamond;
use App\Http\Model\Gift;
use App\Http\Model\GiftBag;
use App\Http\Model\Room;
use App\Lib\Publisher;
use Carbon\Carbon;

class ColorGiftServices extends CommonServices
{
    protected $userModel;
    protected $userWalletModel;
    protected $financeDiamondModel;
    protected $colorGiftModel;
    protected $colorGiftRateModel;
    protected $giftModel;
    protected $luckDrawModel;
    protected $giftBag_model;
    protected $descConf;
    protected $ratioConf;
    protected $service_finance;
    protected $model_room;
    protected $services_room_msg;

    protected $userSendColorGiftList = 'COLOR:GIFT:SEND:LIST:';//zset 用户获得礼物列表 COLOR:GIFT:SEND:LIST:{userId} => {int} {giftname}
    protected $userSendColorGiftInfo = 'COLOR:GIFT:SEND:CHARMINFO:';//zset 用户送礼主播魅力值列表 COLOR:GIFT:SEND:CHARMINFO:{userId} => {int} {userid}
    protected $userAwadColorGiftInfo = 'COLOR:GIFT:AWAD:LIST:';//zset 用户送礼主播收礼列表 COLOR:GIFT:AWAD:LIST:{userId} => {int} {giftNmae - userid}
    protected $colorGiftPoolRateNum = 'COLOR:GIFT:ROUND:POOL:';//对应奖池下的概率次数缓存 COLOR:GIFT:ROUND:POOL:{poolid}
    //上传更新时间
    protected $colorGiftRoundTime = 'COLOR:GIFT:ROUND:LASTTIME:POOL:';//上次更新时间
    protected $error_log = 'error_color_gift';

    public function __construct()
    {
        parent::__construct();

        $this->userModel = new User();
        $this->userWalletModel = new FinanceUserWallet();
        $this->service_finance = new FinanceServices();
        $this->financeDiamondModel = new FinanceDiamond();
        $this->colorGiftModel = new ColorGift();
        $this->colorGiftRateModel = new ColorGiftRateConfig();
        $this->giftModel = new Gift();
        $this->giftBag_model = new GiftBag();
        $this->model_room = new Room();
        $this->services_room_msg = new RoomMsgServices();
        $this->descConf = config('pay.wallet_change_desc');
        $this->ratioConf = config('pay.wallet_change_ratio');

    }

    /**
     * 编辑彩蛋奖池配置
     */
    public function editColorGiftConfig($upData=[]){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($upData)) {
                break;
            }
            $res = $this->colorGiftModel->editColorGiftConfig($upData);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 彩蛋奖池设置奖池开启/关闭
     */
    public function colorGiftSetPoolStatus($poolId, $poolStatus){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($poolId) || empty($poolStatus)) {
                break;
            }
            $pool = $this->colorGiftModel->getColorGiftPool();
            if(empty($pool[$poolId])) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $poolInfo = $pool[$poolId];
            $poolStatus = ($poolStatus==1) ? 1 : 2;
            //开启
            if($poolStatus == 1) {
                //区间内的奖池必须关闭
                if($poolInfo['is_open'] == 1){
                    $code = Hint::ERR_NORMAL;
                    $msg = '奖池未关闭';
                    break;
                }
                $openPool = [];//已开启的奖池
                $openPoolArr = $this->colorGiftModel->getColorGiftPoolByGiftId($poolInfo['gift_id']);
                $openPool =  array_column($openPoolArr,'pool_id');
                //奖池配置数据是否有效
                $poolList = $this->colorGiftModel->getColorGiftPoolConfig($poolId);
                if(empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '获取奖池配置失败';
                    break;
                }
                $flag = 0;
                $giftNumAll = 0;
                foreach($poolList as $val) {
                    if(empty($val['gift_id'])) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '奖池配置 序号'.$val['item_no'].'未配置礼物';
                        $flag = 1;
                        break;
                    }
                    $giftNumAll = $giftNumAll + $val['gift_num'];
                }
                if($giftNumAll < 1) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '奖池配置 礼物数量总和不足1';
                    $flag = 1;
                }
                if($flag == 1) {
                    break;
                }

                //和已开启的奖池比较是否礼物一致
                if(!empty($openPool)) {
                    foreach($openPool as $v){
                        $openPoolList = $this->colorGiftModel->getColorGiftPoolConfig($v);
                        if(empty($openPoolList)) {
                            $code = Hint::PARAM_ERROR;
                            $msg = '已开启奖池配置异常';
                            break;
                        }
                        $openPoolGift = array_column($openPoolList, 'gift_id', 'item_no');
                        $poolGift = array_column($poolList, 'gift_id', 'item_no');
                        foreach($openPoolGift as $k=>$v) {
                            if($poolGift[$k] != $v) {
                                $code = Hint::PARAM_ERROR;
                                $msg = '奖池配置 礼物ID与已开启奖池不一致,奖池序号:'.$k;
                                $flag = 1;
                                break;
                            }
                        }
                        if($flag == 1) {
                            break;
                        }
                    }
                    
                }
                //重制奖池
                $res = $this->colorGiftPoolReset($poolId);
                if($res['code'] != Hint::SUCCESS) {
                    return $res;
                }
            }
            Redis::del($this->colorGiftRoundTime.$poolId);
            $res = $this->colorGiftModel->editColorGiftPool($poolId, ['is_open'=>$poolStatus]);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 新增奖池概率
     */
    public function addPoolRate($poolId, $poolList){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($poolId) || empty($poolList)) {
                break;
            }
            $pool = $this->colorGiftModel->getColorGiftPool();
            if(empty($pool[$poolId])) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $poolMap = $this->colorGiftModel->getColorGiftPoolConfig($poolId);
            if(empty($poolMap)) {
                $code = Hint::PARAM_ERROR;
                $msg = '获取奖池配置失败';
                break;
            }
            $poolMap = array_column($poolMap, null, 'id');
            //奖池需关闭才可改
            if($pool[$poolId]['is_open'] != 2) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池未关闭';
                break;
            }
            //过滤
            $flag = 0;
            foreach($poolList as $val) {
                if(empty($val['gift_id'])) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '奖池配置礼物ID不可为空';
                    $flag = 1;
                    break;
                }
            }
            if($flag == 1) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池配置礼物ID不可为空';
                break;
            }
            //更新
            DB::beginTransaction();
            $finalData = [];
            try {
                //获取目前数据库的最大概率值
                $rate_num = $this->colorGiftModel->getMaxRateNum($poolId);
                $rate_num = !empty($rate_num) ? $rate_num['rate_num'] +1 : 0;
                if(empty($rate_num)){
                    $code = Hint::ERR_NORMAL;
                    $msg = '奖池配置无概率';
                    break;
                }
                foreach($poolList as $k=>$val) {
                    $insert = [
                        'pool_id' => $poolId,
                        'item_no' => $k+1,
                        'gift_id' => $val['gift_id'],
                        'gift_num' => $val['gift_num'],
                        'rate_num' => $rate_num,
                        'is_delete' => 0,
                        'out_rate' => $val['out_rate'],
                    ];
                    $finalData[$k] = $insert;
                    $res = $this->colorGiftModel->addPoolRate($insert);
                    $finalData[$k]['id'] = $res;
                }
                
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $code = Hint::ERROR;
                $msg = '更新系统异常';
                break;
            }
            //重构数据
            foreach($finalData as $k=>$v){
                $giftInfo = $this->giftModel->get_gift($v['gift_id']);
                $data[] = [
                    'id' => $v['id'],
                    'pool_id' => $v['pool_id'],
                    'item_no' => $v['item_no'],
                    'gift_id' => $v['gift_id'],
                    'gift_num' => $v['gift_num'],
                    'gift_name' => $giftInfo['name'],
                    'gift_image' => $giftInfo['image'],
                    'out_rate' => $v['out_rate'],
                    'gift_price' => $giftInfo['price'],
                ];
            }
        }while(false);
        return compact('code','data','msg');
    }

    /**
     * 删除概率
     */
    public function colorGiftRateDel($poolId, $rate_num){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($poolId) || empty($rate_num)) {
                break;
            }
            //更新
            DB::beginTransaction();
            
            try {
                $res = $this->colorGiftModel->colorGiftRateDel($poolId,$rate_num);
                if($res){
                    DB::commit();
                }else{
                    $code = Hint::ERROR;
                    $msg = '概率配置需要大于等于1,本次无法删除';
                    break;
                    DB::rollBack();
                }
               
            } catch (\Exception $e) {
                DB::rollBack();
                $code = Hint::ERROR;
                $msg = '更新系统异常';
                break;
            }

        }while(false);
        return compact('code','data','msg');
    }

    /**
     * 彩蛋礼物保存奖池配置
     */
    public function colorGiftSavePoolConfig($poolId, $poolList){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($poolId) || empty($poolList)) {
                break;
            }
            $pool = $this->colorGiftModel->getColorGiftPool();
            if(empty($pool[$poolId])) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $poolMap = $this->colorGiftModel->getColorGiftPoolConfig($poolId);
            if(empty($poolMap)) {
                $code = Hint::PARAM_ERROR;
                $msg = '获取奖池配置失败';
                break;
            }
            $poolMap = array_column($poolMap, null, 'id');
            //奖池需关闭才可改
            if($pool[$poolId]['is_open'] != 2) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池未关闭';
                break;
            }
            //过滤
            $flag = 0;
            foreach($poolList as $val) {
                if(empty($val['gift_id'])) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '奖池配置礼物ID不可为空';
                    $flag = 1;
                    break;
                }
                if(empty($poolMap[$val['id']])) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '奖池配置ID错误';
                    $flag = 1;
                    break;
                }
            }
            if($flag == 1) {
                break;
            }
            //计算概率是否大于110%
            $allNum = array_column($poolList,'gift_num');
            $allNum = array_sum($allNum);
            $colorGiftPoolInfo = $this->colorGiftModel->getColorGiftPoolInfoByPooId($poolId);
            $giftId = $colorGiftPoolInfo['gift_id'];   
            //彩蛋信息
            $colorInfo = $this->giftModel->get_gift($giftId);
            //总投入钻石
            $inDiamond = $allNum * $colorInfo['price'];
            //总产出钻石
            $outList = $poolList;
            $subtotals = array_map(function($outList) {
                $poolInfo = $this->giftModel->get_gift($outList['gift_id']);
                return $outList['gift_num'] * $poolInfo['price'];
            }, $outList);
            // 使用 array_sum 累加所有的子总计得到总金额
            $total = array_sum($subtotals);
            $outDiamond = $total;
            //计算概率是否大于110%
            $totalRate = intval(($outDiamond/$inDiamond) * 100);
            
            if($totalRate > 110){
                $code = Hint::ERR_NORMAL;
                $msg = '奖池概率有误大于110返奖率';
                break;
            }
            
            //更新
            DB::beginTransaction();
            $upData = [];
            try {
                foreach($poolList as $val) {
                    $id = $val['id'];
                    $giftId = $val['gift_id'];
                    $giftNum = $val['gift_num'];
                    $rate = $val['out_rate'];
                    $upData['gift_id'] = $giftId;
                    $upData['gift_num'] = $giftNum;
                    $upData['out_rate'] = $rate;
                    $res = $this->colorGiftModel->editColorGiftPoolConfig($poolId, $id, $upData);
                }
               
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $code = Hint::ERROR;
                $msg = '更新系统异常';
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 彩蛋礼物新增奖池
     */
    public function colorGiftAddPool($giftId, $poolName, $rate, $minNum, $maxNum, $hours){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($poolName) || empty($minNum) || empty($maxNum)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //新增
            DB::beginTransaction();
            try {
                $poolId = $this->colorGiftModel->addColorGiftPool($giftId, $poolName, $rate, $minNum, $maxNum, $hours);
                if(empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '新增奖池失败';
                    DB::rollBack();
                    break;
                }

                $flag = 0;
                for($i=1;$i<=8;$i++) {
                    $pcId = $this->colorGiftModel->addColorGiftPoolConfig($poolId, $i);
                    if(empty($poolId)) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '新增奖池配置失败';
                        $flag = 1;
                        break;
                    }
                }
                if($flag == 1) {
                    DB::rollBack();
                    break;
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $code = Hint::ERROR;
                $msg = '新增系统异常';
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 彩蛋礼物编辑奖池
     */
    public function colorGiftEditPool($poolId, $poolName, $minNum, $maxNum, $rate, $hours){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($poolId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $pool = $this->colorGiftModel->getColorGiftPool();
            if(empty($pool[$poolId])) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //奖池需关闭才可改
            if($pool[$poolId]['is_open'] != 2) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池未关闭';
                break;
            }

            //更新
            $this->colorGiftModel->editColorGiftPool($poolId, ['pool_name'=>$poolName, 'min_count'=>$minNum, 'max_count'=>$maxNum,'rate'=>$rate, 'hours'=>$hours]);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 彩蛋礼物更新奖池缓存
     */
    public function colorGiftPoolReset($poolId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            try {
                if(empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '更新奖池缓存异常:参数错误';
                    break;
                }
                $poolListArr = $this->colorGiftModel->getColorGiftPoolConfig($poolId);
                if(empty($poolListArr)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '更新奖池缓存异常:数据获取失败';
                    break;
                }
                $rate_num_arr = array_unique(array_column($poolListArr, 'rate_num'));
                foreach($rate_num_arr as $v){
                    $poolListArr = $this->colorGiftModel->getColorGiftPoolConfigV2($poolId,$v);
                    $poolList = array_column($poolListArr, 'gift_num', 'id');
                    $this->colorGiftModel->makeColorGiftPoolData($poolId, $poolList, $v);
                }
                //重置奖池概率
                Redis::SET($this->colorGiftPoolRateNum.$poolId,1);
            } catch (\Exception $e) {
                $code = Hint::ERROR;
                $msg = '更新奖池缓存异常:'.$e->getMessage();
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 彩蛋礼物奖池配置剩余数量
     */
    public function colorGiftPoolConfigNum($poolId, $rate_num){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            try {
                if(empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }
                $now_rate_num = Redis::get($this->colorGiftPoolRateNum.$poolId);

                if(empty($rate_num)){
                    $rate_num = $now_rate_num;
                }
                
                $poolList = $this->colorGiftModel->getColorGiftPoolConfigV2($poolId, $rate_num);
                if(empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }

                $hasList = $this->colorGiftModel->getColorGiftPoolData($poolId, $rate_num);
                if(empty($hasList)){
                    $code = Hint::ERR_NORMAL;
                    $msg = '轮次未获得';
                    break;
                }
                $hasList = array_column($hasList, 'num', 'id');

                $giftIds = array_column($poolList, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach($poolList as $key=>$val) {
                    $val['gift_name'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];
                    $val['gift_price'] = empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price'];
                    $val['less_num'] = empty($hasList[$val['id']]) ? 0 : $hasList[$val['id']];
                    $val['draw_num'] = $val['gift_num'] - $val['less_num'];

                    $poolList[$key] = $val;
                }
                $data['list'] = $poolList;
                $data['now_rate_num'] = $rate_num;//当前查看轮次
                $data['now_use'] = $now_rate_num;//目前使用轮次
                

            } catch (\Exception $e) {
                $code = Hint::ERROR;
                $msg = '异常:'.$e->getMessage();
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 彩蛋礼物抽奖
     */
    public function colorGiftDraw($gift_id, $num, $userId, $room_id, $to_user_ids, $now, $colorGiftInfo){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            $num = abs($num);

            //根据礼物id获取奖池
            $pool = $this->colorGiftModel->getColorGiftPoolByGiftId($gift_id);
            $poolList = [];//已开启的奖池
            $giftToItemNo = [];//奖池礼物对应的奖池序号
            foreach($pool as $val) {
                if($val['is_open'] == 1){
                    //奖池配置数据
                    $poolConfig = $this->colorGiftModel->getColorGiftPoolConfig($val['id']);
                    if(empty($poolConfig)) {
                        continue;
                    }
                    $val['poolConfig'] = $poolConfig;
                    $poolList[] = $val;
                    if(empty($giftToItemNo)) {
                        $giftToItemNo = array_column($poolConfig, 'item_no', 'gift_id');
                    }
                }
            }
            if(empty($poolList)) {
                $code = Hint::WAIT_OPEN;
                break;
            }
            $drawPopList = [];
            foreach($to_user_ids as $toUser)
            {
                $res = $this->do_color_draw($num, $poolList, $userId, $gift_id, $giftToItemNo);

                $drawPopList[$toUser] = $res; //抽奖结果
            }
            $data = $drawPopList;
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 执行抽奖
     */
    public function do_color_draw($num, $poolList, $userId, $color_gift_id, $giftToItemNo){
        //用户总抽奖记录数
        $drawNumNow = $this->colorGiftModel->getUserColorGiftDrawNum($userId);

        //白名单
        $whiteListNow = $this->colorGiftModel->getColorGiftWhiteInfo($userId, $color_gift_id);

        //抽奖
        $drawLogList = [];
        try {
            for($i=1;$i<=$num;$i++) {
                $drawNumNow = $drawNumNow + 1;
                $drawLog = [];
                $drawLog['draw_no'] = $i;
                $drawLog['gift_id'] = 0;
                $drawLog['white_id'] = 0;
                $drawLog['pool_id'] = 0;
                $drawLog['item_no'] = 0;
                $whiteId = 0;
                $is_white = 0;
                $usePool = [];//使用的奖池
                //在范围的
                foreach($poolList as $val) {
                    if($val['min_count']<=$drawNumNow && $drawNumNow<=$val['max_count']) {
                        $usePool = $val;
                    }
                }
                //上一个
                $prevNum = 0;
                if(empty($usePool)) {
                    foreach($poolList as $val) {
                        if($val['max_count']<=$drawNumNow && $prevNum<=$val['max_count']) {
                            $usePool = $val;
                            $prevNum = $val['max_count'];
                        }
                    }
                }
                //下一个
                $nextNum = 0;
                if(empty($usePool)) {
                    foreach($poolList as $val) {
                        if($val['min_count']>=$drawNumNow && ($nextNum==0 || $nextNum>=$val['min_count'])) {
                            $usePool = $val;
                            $nextNum = $val['min_count'];
                        }
                    }
                }
                //还是没有取第一个
                if(empty($usePool)) {
                    $usePool = $poolList[0];
                }

                if(!empty($whiteListNow)) {
                    $whiteInfo = array_shift($whiteListNow);
                    $whiteId = $whiteInfo['id'];
                    //是否删除奖池中的配置
                    if($whiteInfo['delete_pop'] == 1){//删除
                        $whiteCheck = $this->colorGiftModel->checkPopGift($whiteInfo['pop_gift_id'], $usePool['id']);
                        if($whiteCheck){
                            $drawLog['gift_id'] = $whiteInfo['pop_gift_id'];
                            $drawLog['white_id'] = $whiteInfo['id'];
                            $drawLog['item_no'] = empty($giftToItemNo[$whiteInfo['pop_gift_id']]) ? 11 : $giftToItemNo[$whiteInfo['pop_gift_id']];
                            $drawLog['pool_id'] = 9999;
                            $drawLog['pool_rate_num']  = 9999;
                            //减去缓存配置中的奖品
                            $this->colorGiftModel->delPoolGift($usePool['id'],$whiteCheck);
                            $is_white = 1;
                        }
                    }else{
                        //不删除
                        //判断对应的礼物是否在奖池中
                        $whiteCheck = $this->colorGiftModel->checkPopGiftNotLimit($whiteInfo['pop_gift_id'], $usePool['id']);
                        if($whiteCheck){
                            $drawLog['gift_id'] = $whiteInfo['pop_gift_id'];
                            $drawLog['white_id'] = $whiteInfo['id'];
                            $drawLog['item_no'] = empty($giftToItemNo[$whiteInfo['pop_gift_id']]) ? 11 : $giftToItemNo[$whiteInfo['pop_gift_id']];
                            $drawLog['pool_id'] = 9999;
                            $drawLog['pool_rate_num']  = 9999;
                            $is_white = 1;
                        }
                    } 
                }
                if(empty($whiteId) || $is_white==0){
                     //抽取
                    $poolConfigId = $this->colorGiftModel->drawColorGift($usePool['id']);
                    $poolConfigMap = array_column($usePool['poolConfig'], null, 'id');

                    $drawLog['gift_id'] = $poolConfigMap[$poolConfigId]['gift_id'];
                    $drawLog['white_id'] = 0;
                    $drawLog['pool_id'] = $poolConfigMap[$poolConfigId]['pool_id'];
                    $drawLog['item_no'] = $poolConfigMap[$poolConfigId]['item_no'];
                    $drawLog['pool_rate_num'] = (int) Redis::get($this->colorGiftPoolRateNum.$drawLog['pool_id']);
                }
                $drawLog['giftInfo'] = $this->giftModel->get_gift($drawLog['gift_id']);

                $drawLogList[] = $drawLog;  
                //更新白名单
                if(!empty($whiteId) && $is_white==1){
                    $this->colorGiftModel->upWhiteUserInfo($whiteId);
                }  
            }
        } catch (\Exception $e) {
            write_log('error_color_gift', 'do_color_draw 抽奖失败', ['message'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return [];
        }
        //累加用户总抽奖记录数
        $this->colorGiftModel->incrUserDrawNum($userId, $num);

        return $drawLogList;
    }

    //礼物获取角标
    public function giftGetBanner($giftId){

        return build_image('/icon/giftLuck.png');
    }

    //新增彩蛋概率banner
    public function colorGiftRateAddBanner($param){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do{
            if(empty($param['pool_id']) || empty($param['rate_num']) || empty($param['img_url']) || empty($param['jump_url'])) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            DB::beginTransaction();
            try{
                //预备数据
                $insert = [
                    'pool_id' => $param['pool_id'],
                    'rate_num' => $param['rate_num'],
                    'img_url' => $param['img_url'],
                    'jump_url' => $param['jump_url'],
                ];
                //查询是否有数据
                $check = $this->colorGiftModel->getColorGiftRateBanner($param['pool_id'],$param['rate_num']);
                if(!empty($check)){
                    $res = $this->colorGiftModel->colorGiftRateEditBanner($insert,$check['id']);
                }else{
                    $res = $this->colorGiftModel->colorGiftRateAddBanner($insert);
                }
                if($res){
                    $insert['build_img_url'] = build_image($insert['img_url']);
                    $data = $insert;
                }
                
            }catch(\Exception $e){
                write_log('error_colorGift','error 概率banner入库失败',['msg'=>$e->getMessage()]);
                DB::rollBack();
            }
            DB::commit();
        }while(false);
        return compact('code','data','msg');
    }

    //新增彩蛋抽奖白名单
    public function colorGiftWhiteAdd($param){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do{
            $color_gift_id = $param['color_gift_id'];//彩蛋id
            if(empty($color_gift_id)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $whiteUserId = $param['user_id'];//白名单用户
            if(empty($whiteUserId)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $pop_gift_id = $param['pop_gift_id'];//爆出指定礼物id
            if(empty($pop_gift_id)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $is_delete_pool = isset($param['delete_pop']) ? $param['delete_pop'] : 0;//是否删除彩蛋对应概率中的礼物
            $data = [
                'user_id' => $whiteUserId,
                'color_gift_id' => $color_gift_id,
                'pop_gift_id' => $pop_gift_id,
                'delete_pop' => $is_delete_pool,
                'created_at' => Carbon::now()->toDateTimeString(),
            ]; 
            DB::beginTransaction();
            try{
                $res = $this->colorGiftModel->colorGiftWhiteAdd($data);
            }catch(\Exception $e){
                write_log($this->error_log,'error 新增用户白名单失败',['msg'=>$e->getMessage(),'data'=>$data]);
                DB::rollBack();
                $code = Hint::ERR_DB_FAIL;
                $msg = $e->getMessage();
                break;
            }
            DB::commit();

        }while(false);
        return compact('code','msg','data');
    }

    //编辑彩蛋白名单配置
    public function colorWhiteEdit($param){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do{
            $id = $param['id'];
            if(empty($id)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $color_gift_id = $param['color_gift_id'];//彩蛋id
            if(empty($color_gift_id)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $whiteUserId = $param['user_id'];//白名单用户
            if(empty($whiteUserId)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $pop_gift_id = $param['pop_gift_id'];//爆出指定礼物id
            if(empty($pop_gift_id)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            if($param['status'] == 1){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $is_delete_pool = isset($param['delete_pop']) ? $param['delete_pop'] : 0;//是否删除彩蛋对应概率中的礼物
            $data = [
                'user_id' => $whiteUserId,
                'color_gift_id' => $color_gift_id,
                'pop_gift_id' => $pop_gift_id,
                'delete_pop' => $is_delete_pool,
            ]; 
            DB::beginTransaction();
            try{
                $res = $this->colorGiftModel->colorGiftWhiteUpdate($data, $id);
            }catch(\Exception $e){
                write_log($this->error_log,'error 编辑用户白名单失败',['msg'=>$e->getMessage(),'data'=>$data]);
                DB::rollBack();
                $code = Hint::ERR_DB_FAIL;
                $msg = $e->getMessage();
                break;
            }
            DB::commit();

        }while(false);
        return compact('code','msg','data');
    }

    //删除彩蛋白名单
    public function colorWhiteDel($param){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do{
            if(empty($param['delete_id'])){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $update = [
                'is_deleted' => 1,
            ];
            DB::beginTransaction();
            try{
                $res = $this->colorGiftModel->colorGiftWhiteUpdate($update, $param['delete_id']);
            }catch(\Exception $e){
                DB::rollBack();
                write_log($this->error_log,'error 删除彩蛋白名单失败',['msg'=>$e->getMessage(),'id'=>$param['delete_id']]);
                $code = Hint::ERR_DB_FAIL;
                break;
            }
            DB::commit();
        }while(false);
        return compact('code','msg','data');
    }
}